package com.zjw.zy.ext

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.annotation.*
import androidx.lifecycle.LiveData
import androidx.navigation.NavOptions
import androidx.navigation.fragment.findNavController
import com.zjw.zy.R
import com.zjw.zy.base.BaseFragment
import com.zjw.zy.MainActivity
import com.zjw.zy.coreui.fragment.ImageContentFragment
import com.zjw.zy.coreui.fragment.ImagePreviewFragment
import com.zjw.zy.manager.PageManager
import com.zjw.zy.smi.JustWithIt
import com.zjw.zy.utils.PathUtils
import com.zjw.zy.utils.ResourcesUtils
import map.MapActivity
import kotlin.system.exitProcess

/**
 * @author     ：zhong.jw
 * @date       ：Created in 2022/9/26 17:15
 * @description：
 */


fun BaseFragment.go(@IdRes id: Int, args: Bundle? = null, singTop: Boolean = false) {
    findNavController().navigate(id, args, NavOptions.Builder().apply {
        this.setLaunchSingleTop(singTop)
    }.build())
}


fun BaseFragment.goSingleTask(@IdRes id: Int, args: Bundle? = null) {
    val nav = findNavController()
    nav.navigate(id, args, NavOptions.Builder().apply {
        this.setLaunchSingleTop(true)
        this.setPopUpTo(id, false)
    }.build())
}

fun BaseFragment.goForResult(
    @IdRes id: Int,
    args: Bundle? = null,
    singTop: Boolean = false
): LiveData<Any?> {
    val nav = findNavController()
    val live =
        nav.currentBackStackEntry!!.savedStateHandle.getLiveData<Any?>(nav.currentBackStackEntry!!.destination.id.toString())
    go(id, args, singTop)
    return live
}

fun BaseFragment.backWithResult(payload: Any?) {
    val nav = findNavController()
    nav.previousBackStackEntry?.let {
        it.savedStateHandle.getLiveData<Any?>(it.destination.id.toString()).postValue(payload)
    }
    nav.navigateUp()
}

@SuppressLint("RestrictedApi")
fun BaseFragment.popWithResult(@IdRes id: Int, payload: Any?) {
    val nav = findNavController()
    nav.backStack.apply {
        val iterator = this.descendingIterator()
        while (iterator.hasNext()) {
            val next = iterator.next()
            if (next.destination.id == id) {
                next.savedStateHandle.getLiveData<Any?>(id.toString()).postValue(payload)
                break
            }
        }
    }
    nav.popBackStack(id, false)
}


fun BaseFragment.goWithRightAnim(
    @IdRes destination: Int,
    args: Bundle? = null,
    singTop: Boolean = false,
    @AnimRes @AnimatorRes enter: Int = R.anim.default_enter_anim,
    @AnimRes @AnimatorRes exit: Int = -1,
    @AnimRes @AnimatorRes popEnter: Int = -1,
    @AnimRes @AnimatorRes popExit: Int = R.anim.default_exit_anim,
) {
    findNavController().navigate(
        destination, args,
        NavOptions.Builder().setEnterAnim(enter)
            .setExitAnim(exit)
            .setPopEnterAnim(popEnter)
            .setPopExitAnim(popExit)
            .setLaunchSingleTop(singTop)
            .build()
    )
}

fun BaseFragment.goWithTopAnim(
    @IdRes destination: Int,
    args: Bundle? = null,
    singTop: Boolean = false,
    @AnimRes @AnimatorRes enter: Int = R.anim.default_enter_y_anim,
    @AnimRes @AnimatorRes exit: Int = -1,
    @AnimRes @AnimatorRes popEnter: Int = -1,
    @AnimRes @AnimatorRes popExit: Int = R.anim.default_exit_y_anim,
) {
    findNavController().navigate(
        destination, args,
        NavOptions.Builder().setEnterAnim(enter)
            .setExitAnim(exit)
            .setPopEnterAnim(popEnter)
            .setPopExitAnim(popExit)
            .setLaunchSingleTop(singTop)
            .build()
    )
}

fun BaseFragment.back() {
    findNavController().navigateUp()
}

fun BaseFragment.finish() {
    requireActivity().finish()
}

/**
 * main模块使用
 * */
fun BaseFragment.mainActivity(): MainActivity {
    return this.requireActivity() as MainActivity
}

/**
 * map模块使用
 * */
fun BaseFragment.mapActivity(): MapActivity {
    return requireActivity() as MapActivity
}


/**
 * 图片fragment
 * */
fun BaseFragment.goImageContent(
    rootPath: String,
    usingPath: String = "",
    listener: ImageContentFragment.FuncListener? = null
) {

    ImageContentFragment.sListener = listener
    goWithRightAnim(R.id.image_content_fragment, Bundle().apply {
        this.putString(
            ImageContentFragment.IMAGE_ROOT_PATH,
            rootPath
        )
        this.putString(
            ImageContentFragment.IMAGE_USING_PATH,
            usingPath
        )
    })
}

fun BaseFragment.goImagePreview(
    rootPath: String,
    select: String = "",
) {
    go(R.id.nav_image_preview_fragment, Bundle().apply {
        this.putString(
            ImagePreviewFragment.IMAGE_ROOT_PATH,
            rootPath
        )
        this.putString(
            ImagePreviewFragment.IMAGE_PREVIEW_POSITION,
            select
        )
    })
}

/**
 * 挑选图片
 *
 * @param saveFilePath 保存路径
 * @param call 回调路径结果path
 * */
fun BaseFragment.pickUpImage(saveFilePath: String? = null, call: JustWithIt<String>) {
    val requestImageCode = "requestImageCode".hashCode()
    val intent = Intent(Intent.ACTION_PICK)
    intent.type = "image/*"
    //保存修改
    mainActivity().observerActivityResult(requestImageCode) { result, data ->
        if (result == Activity.RESULT_OK) {
            data?.data?.apply {

                if (saveFilePath == null) {
                    //不保存图片
                    PathUtils.getImageRealPathFromURI(this)?.let {
                        call.onWith(it)
                    }

                } else {
                    PathUtils.transferImageToPrivatePath(
                        this,
                        saveFilePath
                    )?.let { it ->
                        call.onWith(it)
                    }
                }

            }
        }
    }
    startActivityForResult(intent, requestImageCode)
}